<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('产品信息新增')"/>
    <th:block th:include="include :: businessCSS"/>
    <style type="text/css">
        .layui-table-view .layui-form-radio {
            margin: 0 5px
        }
        .layui-table-box{padding:0 16px;background: #FFF;border: 0}
        .layui-table-fixed-l{margin-left: 16px}
        .layui-table-fixed-r{margin-right: 16px}
        .layui-table-mend{background: #FFFFFF}
        .layui-table-tool-self{top: 15px}
        .layui-table-tool-temp {
            padding-right: 50px
        }
    </style>
</head>
<body>
<table class="layui-hide" id="dhtable" lay-filter="ftable"></table>
<script type="text/html" id="barDh">
    <a class="layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove" lay-event="del">&nbsp;删除</a>
</script>
<script type="text/html" id="toolbar">
    <div style="padding: 16px;">
        <div class="layui-btn layui-btn-normal layui-table-tools" lay-event="addbtn"
             shiro:hasPermission="business:product:add">
            <p class="dhicon dh-plus" style="color:white;font-size:14px"><span class="fa_span">新增明细</span></p>
        </div>
        <div class="layui-btn layui-btn-warm layui-table-tools" lay-event="exbtn"
             shiro:hasPermission="business:product:add">
            <p class="dhicon dh-external-link-square" style="color:white;font-size:14px"><span class="fa_span">调入</span>
            </p>
        </div>
        <div style="float: right">
            <span class="f_red">*</span>产品分类:
            <div style="display:inline-flex;vertical-align: middle;width:150px">
                <select id="vCpFl" name="vCpFl" th:with="type=${@producttype.queryList()}">
                    <option></option>
                    <div th:each="dict : ${type}" th:utext="'<option value=\''+${dict.vCpLx}+'\' {{ vCpFl==\''+${dict.vCpLx}+'\'?\'selected\':\'\' }}>'+${dict.vCpLxName}+'</option>'" th:remove="tag"><div>
                </select>
            </div>
            <input type="radio" name="fType" value="1" title="含税算未税" {{ fType==1?'checked':'' }}> 
            <input type="radio" name="fType" value="0" title="未税算含税" {{ fType==0?'checked':'' }}>
            <span><font class="f_red">*</font>税率:</span>
            <div style="display:inline-flex;vertical-align: middle;width:150px">
                <input type="text" name="fSl" id="fSl" class="layui-input"
                       style="position:absolute;overflow:hidden;z-index:2;width: 115px;" onkeyup="inputSearch()"
                       onblur="refreshSelect()" autocomplete="off">
                <select id="fSl_select" lay-filter="fSl_select" autocomplete="off" class="layui-select" lay-search
                        th:with="map=${@baseinfosimple.getDropdownData('tb_baseinfo_invoice','fvalue','fvalue')}">
                    <option></option>
                    <div th:each="dict : ${map}" th:utext="'<option value=\''+${dict.vid}+'\' {{ fSl==\''+${dict.vid}+'\'?\'selected\':\'\' }}>'+${dict.vname}+'</option>'" th:remove="tag"><div>
                </select>
            </div>
            <input style="margin-left:10px" class="layui-btn layui-table-tools" type="button" lay-submit=""
                   lay-filter="btn_save" value="保存">
        </div>

    </div>
</script>
<script type="text/html" id="dropdown_vEdi">
    <select lay-filter="vEdi_select" autocomplete="off" class="layui-select" lay-search>
        <option></option>
        <option value='EDI' {{d.vEdi=='EDI'?'selected':''}}>EDI</option>
        <option value='NON-EDI' {{d.vEdi=='NON-EDI'?'selected':''}}>NON-EDI</option>
    </select>
</script>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: businessJS"/>
<th:block th:include="include :: inlineJS"/>
<script type="text/javascript">
    var prefix = ctx + "business/product";
    var vCpFl,fType,fSl;
    var $, layer, form, table, laydate, element;//定义layui模块
    layui.use(['laydate', 'table', 'form', 'layer', 'jquery', 'util', 'element'], function () {
        $ = layui.$, layer = layui.layer, form = layui.form, table = layui.table, laydate = layui.laydate, util = layui.util, element = layui.element;
        $.tablelist.init({
            elem: '#dhtable'
            , data: []
            , page: false
            , even: true
            , limit: 10000
            , totalRow: gridColumns.totalRow
            , cols: [gridColumns.gridBody]
            , toolbar: '#toolbar'
            , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            , height: 'full-36'
            , done: function (res, curr, count) {
                listData = table.cache.dhtable;//每次重载都赋值更新表缓存
                changeDropdownInTable('vEdi', listData);
                changeDropdownInTable('gBrand', listData);
                changeDropdownInTable('gUnit', listData);
                changeDropdown('fSl');//inputSearch无参数，需放到最后
            }
        });
        $.each(gridColumns.gridNewLine, function (v, k) {//明细新增模板修改默认值
            if (k.substring(0, 1) == '#') gridColumns.gridNewLine[v] = $(k).val();
        })
        gridColumns.gridNewLine.deleted = 0;
        //头工具栏事件
        table.on('toolbar(ftable)', function (obj) {
            switch (obj.event) {
                case 'addbtn':
                    listData.push(gridColumns.gridNewLine);
				    reloadTable(listData);
                    form.render();
                    break;
                case 'exbtn':
                    $.modal.open('选择产品', prefix + '/select?pagetype=checkbox', null, null, function (index) {
                        var res = window["layui-layer-iframe" + index].callbackdata();
                        if (res.length > 0) {
                            $.each(res, function (i, v) {
                                table.cache.dhtable.push(v);
                            });
				            reloadTable(table.cache.dhtable);
                            layer.closeAll();
                        } else {
                            layer.msg("请将选择产品移到下方表格！");
                        }
                    });
                    break;
                case 'fieldSet':
                    filedSet(moduleTable);
                    break;
            }
            ;
        });
        //编辑表格监听
        table.on('edit(ftable)', function (obj) {
            var selector = obj.tr.selector + ' td[data-field="' + obj.field + '"] div';
            var oldtext = $(selector).text();// 单元格编辑之前的值
            var editField = obj.field,//编辑单元格fieId
                editRow = obj.data,//编辑单元格行数据
                dataindex = $(obj.tr.selector).attr('data-index'),//编辑单元格下标
                isReturn, editValue;
            if (decimalObj[obj.field] > -1) {//判断是否数值字段
                editValue = checkEdit(obj, decimalObj);//判断输入是否为数值，否则还原数值
                if (!editValue) {
                    editValue = oldtext;
                    listData[dataindex][editField] = oldtext;
                    isReturn = 1;
                }
                if (!isReturn) {//输入的是数值并且改单元格是数值格式字段fSl
                    var fXsFpsl = Number($("#fSl").val() ? $("#fSl").val() : 0);//税率
                    if (editField == 'fWsMj') {//未税面价
                        listData[dataindex]['fHsMj'] = Number(editValue * (100 + fXsFpsl) / 100).toFixed(decimalObj.fHsMj);//含税面价
                        obj.update({fHsMj: listData[dataindex]['fHsMj']});
                    }
                    if (editField == 'fHsMj') {//含税面价
                        listData[dataindex]['fWsMj'] = Number(editValue * 100 / (100 + fXsFpsl)).toFixed(decimalObj.fWsMj);//未税面价
                        obj.update({fWsMj: listData[dataindex]['fWsMj']});
                    }
                }
                setTableValue('dhtable', dataindex, editField, editValue);//通过dom给表格内控件渲染值
                listData[dataindex][editField] = editValue;
            }
        });
        //监听行事件
        table.on('tool(ftable)', function (obj) {
            var data = obj.data, event = obj.event;
            switch (event) {
                case "del":
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    listData = table.cache.dhtable;
                    for (var i = 0; i < listData.length; i++) if (!listData[i] || listData[i].length == 0) listData.splice(i, 1);//删除一项
				    reloadTable(listData);
                    break;
            }
        });
        form.on('submit(btn_save)', function (data) {
            if (data.field.vCpFl) {
                if (data.field.fType) {
                    if (data.field.fSl) {
                        //【品牌、型号、规格、品名、系列、单位】去除前后空格回车
                        var filterBlankArr = ['gBrand', 'gID', 'gModel', 'gName', 'gSerial', 'gUnit'];
                        $.each(filterBlankArr, function (i, v) {
                            $.each(table.cache.dhtable, function (ii, vv) {
                                if (vv[v]) vv[v] = vv[v].replace(/(^\s*)|(\s*$)/g, "").replace(/[\r\n]/g, "");
                            })
                        })
                        $.operate.post(prefix + "/addpost", {
                            'productInfoItems': JSON.stringify(table.cache.dhtable, null, 2),
                            'vCpFl': $("#vCpFl").val(),
                            'fSl': $('#fSl').val(),
                            'fType': $("[name='fType']:checked").val()
                        }, function (res) {
                            if (res.code == 0) goUrl(prefix + "/add")
                        });
                    } else $.modal.msgError("请选择税率！", modal_status.FAIL);
                } else $.modal.msgError("请选择税额计算相关！", modal_status.FAIL);
            } else $.modal.msgError("请选择产品分类！", modal_status.FAIL);
        });
    });
    function reloadTable(data){
        vCpFl = $('#vCpFl').val();
        fType = $('[name="fType"]:checked').val();
        fSl = $('#fSl').val();
        table.reload('dhtable', {data : data});
    }
    function dropdownInTable(dropDownEditList, listData) {
        $.each(dropDownEditList, function (i, v) {
            changeDropdownInTable(v, listData);
        });
    }
</script>
</body>
</html>